package org.example;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.hutool.poi.excel.StyleSet;
import com.alibaba.fastjson2.JSON;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.SheetUtil;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFSheet;

import java.io.File;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Hello world!
 *
 */
public class App1
{
    public static void main ( String[] args ) throws Exception
    {
        String month = "";
        Set<String> nameSet = new HashSet<>();

        HashMap<String,Set<String>> swapNameMap = new HashMap<>();
        initSwapNameMap(swapNameMap);

        HashMap<String,String> songAlbumMap = new HashMap<>();

        String path = "D:\\ddd\\123\\";
        File file = new File(path);
        File[] files = file.listFiles();
        Map<String,List<Map<String,Object>>> fileMap = new HashMap<>();
        for (File temp : files) {
            String fileName = temp.getName();
            if(fileName.startsWith("aiting") || fileName.startsWith("mv") || fileName.startsWith("single") || fileName.startsWith("song")){
                if(fileName.startsWith("song")){
                    month = fileName.split("_")[6].substring(0,6);
                }
                ExcelReader reader = ExcelUtil.getReader(temp);
                List<Map<String,Object>> dataAll = reader.readAll();
                fileMap.put(fileName,dataAll);
                for (int i = 0; i < dataAll.size(); i++) {
                    Map<String, Object> objectMap = dataAll.get(i);
                    String name = objectMap.get("歌手名").toString();
                    nameSet.add(name);
                }
            }
        }
        excuteNameSet(nameSet,swapNameMap);
        for (String name : nameSet) {
            songAlbumMap.clear();
            Set<String> swapNameSet = swapNameMap.get(name);
            if(swapNameSet==null){
                swapNameSet = new HashSet<>();
            }
            File nameFile = new File(path+"file/" + name + month + "结算明细.xlsx");

            ExcelWriter writer = ExcelUtil.getWriter(nameFile);
            List<Music> allMusic = new ArrayList<>();
            for (Map.Entry<String,List<Map<String,Object>>> entry : fileMap.entrySet()){
                String fileName = entry.getKey();
                List<Map<String,Object>> data = entry.getValue();
                Set<String> finalSwapNameSet = swapNameSet;

                for(Map<String, Object> map : data){
                    String userName = map.get("歌手名").toString();
                    if(name.equals(userName) || finalSwapNameSet.contains(userName)){
                        Music music = new Music(map,fileName);
                        allMusic.add(music);
                        if(StringUtils.isNotBlank(music.getAlbumTitle())){
                            songAlbumMap.put(music.getSongName().replace("(Live)",""),music.getAlbumTitle());
                        }
                    }
                }
            }
            for(Music music : allMusic){
                if(StringUtils.isBlank(music.getAlbumTitle())){
                    String album = songAlbumMap.get(music.getSongName());
                    if(album==null){
                        music.setAlbumTitle("***");
                    }else{
                        music.setAlbumTitle(album);
                    }

                }
            }
            writer.setSheet("明细");
            writer.write(allMusic,true);
            writer.setSheet(0);
            writer.renameSheet("汇总");
            List<Map<String, Object>> excelData = new ArrayList<>();
            Map<String, List<Music>> platformMap = allMusic.stream().collect(Collectors.groupingBy(Music::getPlatform));
            for(Map.Entry<String,List<Music>> entry : platformMap.entrySet()){
                Map<String,Object> row= new LinkedHashMap<>();
                String platform = entry.getKey();
                row.put("平台",platform);
                Map<String, List<Music>> albumMap = entry.getValue().stream().collect(Collectors.groupingBy(Music::getAlbumTitle));
                for(Map.Entry<String,List<Music>> entry1 : albumMap.entrySet()){
                    String album = entry1.getKey();
                    row.put(album,entry1.getValue().stream().map(Music::getMoney).reduce(BigDecimal.ZERO,BigDecimal::add));
                }
                excelData.add(row);
            }
            Map<String, List<Music>> albumMap = allMusic.stream().collect(Collectors.groupingBy(Music::getAlbumTitle));
            Map<String,Object> row= new LinkedHashMap<>();
            //Map<String,Object> row1= new LinkedHashMap<>();
            row.put("平台","汇总");
           // row1.put("平台","总和");
            for(Map.Entry<String,List<Music>> entry1 : albumMap.entrySet()){
                String album = entry1.getKey();
                row.put(album,entry1.getValue().stream().map(Music::getMoney).reduce(BigDecimal.ZERO,BigDecimal::add));
            }
            //row1.put("总和",);
            excelData.add(row);
            //excelData.add(row1);
            writer.write(excelData,true);
            List<Object> row1 = CollUtil.newArrayList("总和", allMusic.stream().map(Music::getMoney).reduce(BigDecimal.ZERO,BigDecimal::add));
            writer.writeRow(row1,true);
            StyleSet style = writer.getStyleSet();
            Font font = writer.createFont();
            font.setColor(IndexedColors.BLACK.getIndex());
            font.setBold(true);
            font.setFontHeightInPoints((short) 16);
            //重点，设置中文字体
            font.setFontName("宋体");
            CellStyle headCellStyle = style.getHeadCellStyle();
            headCellStyle.setFont(font);

            int sheetCount = writer.getSheetCount();
            for(int k=0;k<sheetCount;k++){
                writer.setSheet(k);
                writer.setRowHeight(0,k==0?30:45);
                writer.autoSizeColumnAll();
            }
            writer.close();
        }
    }

    public static void excuteNameSet(Set<String> nameSet,HashMap<String,Set<String>> swapNameMap){
        swapNameMap.values().forEach(a->{
            nameSet.removeAll(a);
        });
        Set<String> removedNames = new HashSet<>();
        ArrayList<String> nameList = new ArrayList<>(nameSet);
        Collections.sort(nameList, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o1.length() - o2.length();
            }
        });
        for (int i = 0; i < nameList.size(); i++) {
            String name = nameList.get(i);
            nameSet.forEach(a->{
                if(name.length()>a.length() && name.indexOf(a)>=0){
                    removedNames.add(name);
                    Set<String> names = swapNameMap.get(a);
                    if(names==null){
                        names = new HashSet<>();
                    }
                    names.add(name);
                    swapNameMap.put(a,names);
                }
            });
        }
        nameSet.removeAll(removedNames);
    }

    public static void initSwapNameMap(HashMap<String,Set<String>> swapNameMap){
        Set<String> nameSet = new HashSet<>();
        nameSet.add("The Verse");
        swapNameMap.put("陈绮贞",nameSet);
    }
}
